package com.dbb.trade.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public final class ImageUtil {
	
	private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
	
	private ImageUtil() {}
	
	public static final float SOFTEN_FACTOR = 0.05f;
	public static final Integer THREE = 3;
	public static final Integer FOUR = 4;

	public static void resize(String originalFile, String resizedFile, int newWidth, int type) throws IOException {
		resize(originalFile, resizedFile, newWidth, 1, type);
	}
	
	public static void resize(String originalFile, String resizedFile, int newWidth) throws IOException {
		resize(originalFile, resizedFile, newWidth, 1, 0);
	}
	//1.定宽 2.定高 3.最大边
	public static void resize(String originalFile, String resizedFile,
			int border, float quality, int type) throws IOException {

		ImageIcon ii = new ImageIcon(originalFile);
		Image i = ii.getImage();
		Image resizedImage = null;

		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);

		if(type == 1) {
			resizedImage = i.getScaledInstance(border, (border * iHeight) / iWidth, Image.SCALE_SMOOTH);
		} else if (type == 2) {
			resizedImage = i.getScaledInstance((border * iWidth)/iHeight, border, Image.SCALE_SMOOTH);
		} else {
			if (iWidth > iHeight) {
				resizedImage = i.getScaledInstance(border, (border * iHeight) / iWidth, Image.SCALE_SMOOTH);
			} else {
				resizedImage = i.getScaledInstance((border * iWidth) / iHeight, border, Image.SCALE_SMOOTH);
			}
		}
		// This code ensures that all the pixels in the image are loaded.
		Image temp = new ImageIcon(resizedImage).getImage();

		// Create the buffered image.
		BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
				temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

		// Copy image to buffered image.
		Graphics g = bufferedImage.createGraphics();

		g.setColor(Color.white);
		g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
		g.drawImage(temp, 0, 0, null);
		g.dispose();

		float[] softenArray = { 0, SOFTEN_FACTOR, 0, SOFTEN_FACTOR,
				1 - (SOFTEN_FACTOR * FOUR), SOFTEN_FACTOR, 0, SOFTEN_FACTOR, 0 };
		Kernel kernel = new Kernel(THREE, THREE, softenArray);
		ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
		bufferedImage = cOp.filter(bufferedImage, null);

		// Write the jpeg to a file.
		FileOutputStream out = new FileOutputStream(resizedFile);

		// Encodes image as a JPEG data stream
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);

		param.setQuality(quality, true);

		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);
		out.close();
	}

	public static void resizeMaxBorder(String originalFile, String resizedFile,
			int newWidth, float quality) throws IOException {

		ImageIcon ii = new ImageIcon(originalFile);
		Image i = ii.getImage();
		Image resizedImage = null;

		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);

		if (iWidth > iHeight) {
			resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
					/ iWidth, Image.SCALE_SMOOTH);
		} else {
			resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
					newWidth, Image.SCALE_SMOOTH);
		}
		// This code ensures that all the pixels in the image are loaded.
		Image temp = new ImageIcon(resizedImage).getImage();

		// Create the buffered image.
		BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
				temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

		// Copy image to buffered image.
		Graphics g = bufferedImage.createGraphics();

		// Clear background and paint the image.
		g.setColor(Color.white);
		g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
		g.drawImage(temp, 0, 0, null);
		g.dispose();

		// Soften.
		float[] softenArray = { 0, SOFTEN_FACTOR, 0, SOFTEN_FACTOR,
				1 - (SOFTEN_FACTOR * FOUR), SOFTEN_FACTOR, 0, SOFTEN_FACTOR, 0 };
		Kernel kernel = new Kernel(THREE, THREE, softenArray);
		ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
		bufferedImage = cOp.filter(bufferedImage, null);

		// Write the jpeg to a file.
		FileOutputStream out = new FileOutputStream(resizedFile);

		// Encodes image as a JPEG data stream
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);

		param.setQuality(quality, true);

		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);
		out.close();
	} // Example usage

	
	public static void resize(InputStream is, String path, int w, Color c) {
		resize(is, path, w, w, 1f, c);
	}
	
	private static void resize(InputStream is, String f, int w, int h, float per, Color backgroundColor) {
		Image src;
		try {
			src = javax.imageio.ImageIO.read(is); 
			String imgMidname = f;
			int oldW = src.getWidth(null); 
			int oldH = src.getHeight(null);
			int newW = 0;
			int newH = 0; 

			double w2 = (oldW * 1.00) / (w * 1.00);
			double h2 = (oldH * 1.00) / (h * 1.00);

			// 图片跟据长宽留白，成一个正方形图。
			BufferedImage oldpic;
			if (oldW > oldH) {
				oldpic = new BufferedImage(oldW, oldW,
						BufferedImage.TYPE_INT_RGB);
			} else {
				if (oldW < oldH) {
					oldpic = new BufferedImage(oldH, oldH,
							BufferedImage.TYPE_INT_RGB);
				} else {
					oldpic = new BufferedImage(oldW, oldH,
							BufferedImage.TYPE_INT_RGB);
				}
			}
			Graphics2D g = oldpic.createGraphics();
			g.setColor(backgroundColor);
			if (oldW > oldH) {
				g.fillRect(0, 0, oldW, oldW);
				g.drawImage(src, 0, (oldW - oldH) / 2, oldW, oldH,
						backgroundColor, null);
			} else {
				if (oldW < oldH) {
					g.fillRect(0, 0, oldH, oldH);
					g.drawImage(src, (oldH - oldW) / 2, 0, oldW, oldH,
							backgroundColor, null);
				} else {
					g.drawImage(src.getScaledInstance(oldW, oldH,
							Image.SCALE_SMOOTH), 0, 0, null);
				}
			}
			g.dispose();
			src = oldpic;
			// 图片调整为方形结束
			if (oldW > w) {
				newW = (int) Math.round(oldW / w2);
			} else {
				newW = oldW;
			}
			if (oldH > h) {
				newH = (int) Math.round(oldH / h2);
			} else {
				newH = oldH;
			}
			BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(
					src.getScaledInstance(newW, newH, Image.SCALE_SMOOTH), 0,
					0, null);
			FileOutputStream newimage = new FileOutputStream(imgMidname); 
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			/* 压缩质量 */
			jep.setQuality(per, true);
			encoder.encode(tag, jep);
			// encoder.encode(tag); //近JPEG编码
			newimage.close();
		} catch (IOException ex) {
			logger.warn(ex.getMessage());
		}
	}

	public static void main(String[] args) throws IOException {
		pressImagec("D:\\mvn_version\\shlll4\\2.webdesign\\HTML CODE\\photography\\css_shlll4_photo\\image\\watermark.png", "d:\\tmp\\detail\\402881eb3bd4d68b013bd4d9be2c0000.jpg");
	}

	public static void pressImagec(String pressImg, String targetImg) {   
        try {   
            File file = new File(targetImg);   
            Image src = ImageIO.read(file);   
            int wideth = src.getWidth(null);   
            int height = src.getHeight(null);   
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);   
            Graphics g = image.createGraphics();   
            g.drawImage(src, 0, 0, wideth, height, null);   
  
            File filebiao = new File(pressImg);   
            Image srcBiao = ImageIO.read(filebiao);   
            int widethBiao = srcBiao.getWidth(null);   
            int heightBiao = srcBiao.getHeight(null);   
            g.drawImage(srcBiao, wideth - widethBiao, 0, widethBiao, heightBiao, null);   
            g.dispose();   
            FileOutputStream out = new FileOutputStream(targetImg);   
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(image);   
            out.close();   
        } catch (Exception ex) {   
        	logger.warn(ex.getMessage());
        }   
    }   
}
